﻿var Common = {
	shuffle: function(arr) { // 洗牌
		for (var i = arr.length; i >= 1; i--) {
			var j = parseInt(Math.random() * i);
			var t = arr[i - 1];
			arr[i - 1] = arr[j];
			arr[j] = t;
		}
		return arr;
	},
	regEscape: function(s) {
		return s.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
	},
	random: function(arr) {
		if (!arr || !arr.length) return;
		return arr[parseInt(arr.length * Math.random())];
	},
	format: function(template, json) { // 格式化 ${0}、${attr}
		if (!json) return template;
		return template.replace(/\$\{(.+?)\}/g, function() {
			return json[arguments[1]];
		});
	},
	$: function(id) { // 获取元素
		return document.getElementById(id);
	},
	setCookie: function(name, value, days) { // 设置读取cookie
		document.cookie = name + "=" + escape(value) + 
			(days ? "; expires=" + new Date(new Date().getTime() + 
			days * 24 * 60 * 60 * 1000).toGMTString() : "");
	},
	getCookie: function(name) {
		var match = document.cookie.match(new RegExp("(^|;)\\s*(" + name + ")=([^;]*)(;|$)", "i"));
		if (!match) return;
		return unescape(match[3]);
	},
	getParam: function(url, name, def) { // 获取url参数
		var match = ("" + url).match(new RegExp("(\\?|&)\\s*(" + name + ")\=([^&]*)(&|$)"));
		return match ? unescape(match[3]) : def;
	},
	loadScript: function(url, charset) { // 加载脚本
		var script = document.createElement("script");
		if (charset) script.charset = charset;
		script.type = "text/javascript";
		script.defer = "true";
		script.src = url;
		var parent = document.getElementsByTagName("head")[0] || document.documentElement;
		if (parent && parent.insertBefore) parent.insertBefore(script, parent.firstChild);
	},
	loadCss: function(css, charset) { // 加载样式表
		var css = document.createElement("link");
		css.type = "text/css";
		if (charset) css.charset = charset;
		css.rel = "Stylesheet";
		css.href = url;
		var parent = document.getElementsByTagName("head")[0] || document.documentElement;
		if (parent && parent.insertBefore) parent.insertBefore(css, parent.firstChild);
	},
	setEvent: function(target, name, func) {
		if (target.addEventListener)
			target.addEventListener(name, func, false);
		else if (target.attachEvent)
			target.attachEvent("on" + name, func);
	},
	xmlEncode: function(str) { // xml字符编码
		var self = this;
		return str.replace(/[\x00-\x60]/g, function() {
			return self.format("&#${0};", [arguments[0].charCodeAt(0)]);
		});
	},
	htmlDict: {"amp": "&", "quot": '"', "lt": "<", "gt": ">", "nbsp": " "},
	htmlDecode: function(html) { // html解码
		var self = this;
		return html.replace(/&([^;]+);/g, function($0, $1) {
			if (self.htmlDict[$1]) return self.htmlDict[$1];
			var match = $1.match(/^#(\d+)$/);
			if (match) return String.fromCharCode(+match[1]);
			return $0;
		}).replace(/<br\s*\/?>/g, "\r\n");
	}
};